package com.hantanger.weblog.controller;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.hantanger.weblog.model.User;
import com.hantanger.weblog.util.HtmlUtil;
import com.hantanger.weblog.util.UserHelper;

/**
 * 登录，登出
 * 
 * @author lys
 * 
 */
public class LoginoutController extends BaseController {

	/**
	 * 登录页面及处理登出请求
	 */
	@Override
	public String doGet(HttpServletRequest request, HttpServletResponse response) {
		String type = HtmlUtil.getString(request, "type", null);
		if("out".equalsIgnoreCase(type)){
			request.getSession().invalidate();
			try {
				response.sendRedirect("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		if (UserHelper.isLogined()) {
			try {
				response.sendRedirect("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		return "login";
	}

	/**
	 * 登录设置
	 */
	@Override
	public String doPost(HttpServletRequest request,
			HttpServletResponse response) {
		if (UserHelper.isLogined()) {
			try {
				response.sendRedirect("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		String email = HtmlUtil.getString(request, "email", null);
		String password = HtmlUtil.getString(request, "password", null);
		if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
			return null;
		}
		User user = getUserDao().getUserByEmail(email);
		if (user == null || !user.getPassword().equals(password)) {
			request.setAttribute("loginError", true);
			return "login";
		}
		try {
			HttpSession session = request.getSession();
			session.setAttribute("userEmail", email);
			response.sendRedirect("/");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
